/**
 * 权限管理下的角色管理模块
 */
const db = require('../db/index')
const { Op } = require("sequelize")
const crypto = require('crypto')
const sequelize = require('sequelize')

//引入角色模型
const initModels = require('../models/init-models')
const Menu = initModels(db).info_menus
const moment = require('moment');
//引入生成树形结构的方法
const { listToTree } = require('../util/index')

//获取所有菜单
exports.getAllMenus = async (req,res) => {
    try{
        await db.sync()
        const result = await Menu.findAll({
            order: [
                ['level','ASC']
            ]
        })
        res.dataSend('查询成功！',0,listToTree(result))
    }catch (error){
        res.cc(error)
    }
}
//添加菜单
exports.addMenu = async (req,res) => {
    //接收表单数据
    const { menuName, code, parentId, level } = req.body
    try{
        await db.sync()
        //生成id
        const id = crypto.randomUUID()
        //生成时间
        const createTime = moment().format('YYYY-MM-DD HH:mm:ss')
        const updateTime = moment().format('YYYY-MM-DD HH:mm:ss')
        let addResult = await Menu.create({
            id,
            createTime,
            updateTime,
            menuName,
            code,
            parentId,
            level:level+1
        })
        let updateResult = await Menu.update({
            children: sequelize.literal(`
              CASE
                WHEN COALESCE(TRIM(children), '') = '' THEN 
                  '${id}'
                ELSE 
                  CONCAT(children, ',${id}')
              END
            `)
        },{
            where:{
                id: parentId
            }
        })
        if(addResult === null || updateResult === null){
            return res.cc('添加菜单失败，请稍后再试！')
        }
        res.cc('添加成功！',0)
    } catch (error) {
        res.cc(error)
    }
}
//修改菜单
exports.updateMenu = async (req,res) => {
    //接收表单数据
    const { id, menuName, code } = req.body
    try{
        await db.sync()
        //更新时间
        const updateTime = moment().format('YYYY-MM-DD HH:mm:ss')
        let addResult = await Menu.update({
            menuName,
            code,
            updateTime}, {
            where: {
                id: id
            }
        })
        if(addResult === null){
            return res.cc('修改菜单失败，请稍后再试！')
        }
        res.cc('修改成功！',0)
    } catch (error) {
        res.cc(error)
    }
}
//删除菜单
exports.deleteMenu = async (req,res) => {
    const {ids,parentId,id} = req.body
    try {
        await db.sync()
        //删除当前元素及其子元素
        const result = await Menu.destroy({
            where:{
                id: {
                    [Op.in]: ids
                }
            }
        })
        //更新时间
        const updateTime = moment().format('YYYY-MM-DD HH:mm:ss')
        //修改父元素的children
        const updateResult = await Menu.update({
            children: sequelize.literal(`
              CASE
                WHEN children LIKE '%,${id}' THEN 
                  REPLACE(children, ',${id}', '')
                WHEN children = '${id}' THEN 
                  ''
                ELSE 
                  REPLACE(children, '${id},', '')
              END
            `),
            updateTime
        },{
            where: {
                id: parentId
            }
        })
        if(result === null || updateResult === null){
            return res.cc('删除菜单失败，请稍后再试！')
        }
        res.cc('删除成功！',0)
    }catch (error){
        res.cc(error)
    }
}
